/*
 * @Author: 谢小康 2170673706@qq.com
 * @Date: 2023-12-08 14:06:04
 * @LastEditors: 谢小康 2170673706@qq.com
 * @LastEditTime: 2024-01-21 15:14:48
 * @FilePath: \My-bolg\server\serve\users.js
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
const M_USer = require('../model/users.js');
const article = require("../model/article.js")
const configg = require('../model/config.js');
const Friends = require('../model/friends.js');
const Lables = require('../model/lables.js');
const articleAndLable = require('../model/articleAndLable.js');
const sequelize = require('../model/db.js');
const { Op } = require("sequelize");
class User {
    /* 登录查询用户名 */
    async login(username) {
        const user = await M_USer.findOne({ where: { Users_name: username } })
        if (user) {
            return {
                msg: "查询成功",
                code: 1,
                users: {
                    Users_role: user.Users_role,
                    id: user.id,
                    Users_address: user.Users_address,
                    Users_name: user.Users_name,
                    Users_password: user.Users_password,
                    Users_corver: user.Users_corver
                }
            }
        } else {

            return {
                user: null,
                msg: '用户名不存在',
                code: 0
            }
        }
    }
    /* 查询用户 */
    async getUserByID(id) {
        const user = await M_USer.findOne({ where: { id: id } });
        if (user == null) {
            return {
                users: null,
                msg: '用户不存在',
                code: 0
            }
        } else {
            /* 查询到用户 */
            return {
                msg: "查询成功",
                code: 1,
                users: {
                    id: user.id,
                    Users_address: user.Users_address,
                    Users_name: user.Users_name,
                    Users_corver: user.Users_corver,
                    Users_role: user.Users_role
                }
            }
        }
    }
    /* 修改 */
    async updatauser(userinfo) {
        let { name, avatar } = userinfo
        const user = await M_USer.update({
            Users_name: name,
            Users_corver: avatar
        }, { where: { id: userinfo.id } });
        if (user[0] == 1) {
            return {
                code: 1,
                msg: '修改成功'
            }
        } else {
            return {
                code: 0,
                msg: '修改失败'
            }
        }
    }
    async updatapaword(password, oldpassword, id) {
        const user = await M_USer.update({
            Users_password: password
        }, {
            where: { Users_password: oldpassword, id: id }
        })
        console.log(user);
        if (user[0] == 1) {
            console.log(1111111);
            return {
                code: 1,
                msg: '修改成功'
            }
        } else {
            return {
                code: 0,
                msg: '修改失败'
            }
        }
    }
    async findoneUserbyname(Users_name) {
        const user = await M_USer.findOne({ where: { Users_name } });
        if (user == null) {
            return {
                users: null,
                msg: '用户不存在',
                code: 0
            }
        } else {
            /* 查询到用户 */
            return {
                msg: "查询成功",
                code: 1,
                users: {
                    id: user.id,
                    Users_address: user.Users_address,
                    Users_name: user.Users_name,
                    Users_corver: user.Users_corver,
                    Users_role: user.Users_role
                }
            }
        }
    }
    async addUser(Users_name, Users_password, Users_address) {
        const user = await M_USer.create({
            Users_name,
            Users_password,
            Users_address,
            Users_role: 3,
            Users_corver: "http://imgfile.xxkdjy.top/2024011919245858472.jpg"
        })
        if (user) {
            return {
                code: 1,
                msg: "添加成功"
            }
        } else {
            return {
                code: 0,
                msg: "添加失败"
            }
        }
    }
    async getsitedata() {
        let articleunm = article.count({
            where: { article_status: 1 }, // 查询状态为1的文章数量，即已发布的文章数量
        })
        let view = configg.findOne({
            attributes: ["Bolog_view"],
            where: {
                id: 1
            }
        })
        let lablesunm = Lables.count()

        let friendnum = Friends.count({
            where: { friend_status: 1 }, // 查询状态为1的友链数量，即已通过的友链数量
        })
        let ress = await Promise.all([view, articleunm, lablesunm, friendnum])
        ress[0] = ress[0].dataValues.Bolog_view || 0//浏览量
        const [results] = await sequelize.query("select count(article_status),DATE_FORMAT(createdAt,'%Y-%m') from article WHERE article_status=1 GROUP BY DATE_FORMAT(createdAt,'%Y-%m')")
        let unmm = results.map(item => {
            return {
                num: item["count(article_status)"],
                time: item["DATE_FORMAT(createdAt,'%Y-%m')"]
            }
        })
        const [res] = await sequelize.query("select count(lable_id),lable_id from article_lable  GROUP BY lable_id")
        let promise = []
        let ok = res.map(item => {
            return {
                lable_id: item["lable_id"],
                num: item["count(lable_id)"]
            }
        })
        ok.forEach(item => {
            promise.push(Lables.findOne({
                where: {
                    id: item.lable_id
                }
            }))
        })
        let lable = await Promise.all(promise)
        let i = 0
        let lableunm = lable.map(item => {
            return {
                name: item.dataValues.lable_name,
                num: ok[i++].num
            }
        })
        return {
            code: 1,
            msg: "获取成功",
            data: {
                view: ress[0],
                articleunm: ress[1],
                lablesunm: ress[2],
                friendnum: ress[3],//友链数量,
                articletime: unmm,
                labletime: lableunm,
            }
        }
    }
    async getalluser(page, pageSize, keyword) {
        page = (typeof page == "string") ? parseInt(page) : page;
        pageSize = (typeof pageSize == "string") ? parseInt(pageSize) : pageSize;
        let whereobj = {}
        let count
        keyword && Object.assign(whereobj, {
            Users_name: {
                [Op.like]: `%${keyword}%`,
            }
        })
        let users = await M_USer.findAll({
            where: whereobj,
            offset: (page - 1) * pageSize,
            limit: pageSize,
            attributes: { exclude: ['Users_password'] },
        })
        let data = users.map(item => item.dataValues)

        if (data.length == 0) {
            return {
                code: 0,
                msg: "暂无数据",
                data: {
                    data: null,
                    count: 0
                }
            }
        } else {
            if (keyword) {
                count = await M_USer.count({
                    where: whereobj
                })
            }
            return {
                code: 1,
                msg: "获取成功",
                data: {
                    data,
                    count,
                }
            }
        }

    }
    async getuserNum() {
        let res = await M_USer.count()
        return {
            code: 1,
            msg: "获取成功",
            data: res
        }
    }
    async deleteuser(idlist) {
        let res = await M_USer.destroy({
            where: {
                id: {
                    [Op.in]: idlist
                }
            }
        })
        if (res > 0) {
            return {
                code: 1,
                msg: "删除成功"
            }
        } else {
            return {
                code: 0,
                msg: "删除失败"
            }
        }
    }
    async changeRole(id, role) {
        let res = await M_USer.update({
            Users_role: role
        }, {
            where: {
                id
            }
        })
        if (res > 0) {
            return {
                code: 1,
                msg: "修改成功"
            }
        } else {
            return {
                code: 0,
                msg: "修改失败"
            }
        }
    }
}
module.exports = new User();